window.__GlobalCache__ = {};

import Vue from 'vue';

const state = {
    cacheArray: [],
    cacheObj: {},
};
const getters = {};
const mutations = {};
const actions = {
    getRenderData(context) {
        context.state.cacheObj = {};
        // action=> 获取全部缓存数据
        window.action.cache.getAll().then((obj) => {
            var res = obj.res;
            var localRes = obj.localRes;
            var _localRes = {};
            for (let i = 0; i < localRes.length; i++) {
                const element = localRes[i];
                _localRes[element.key] = element.value;
            };
            for (let i = 0; i < res.length; i++) {
                const element = res[i];
                if (_localRes.hasOwnProperty(element.key)) {
                    element.value = _localRes[element.key];
                } else {
                    element.value = '';
                };
                context.state.cacheObj[element.key] = element.value;
            };
            context.state.cacheArray = res;
        })
    },
    creatCache(context, param) {
        // action=> 创建缓存数据
        window.action.cache.creat({
            key: param.key,
            value: param.value,
            name: param.name,
        }).then((res) => {
            if (res) {
                param.callback();
                context.dispatch('getRenderData');
            };
        });
    },
    updataCache(context, param) {
        if (context.state.cacheObj.hasOwnProperty(param.key)) {
            // action=> 更新缓存数据
            window.action.cache.update({
                id: param.id,
                key: param.key,
                value: param.value,
            }).then((res) => {
                if (res) {
                    param.callback();
                    context.dispatch('getRenderData');
                };
            });
        } else {
            context.dispatch('getRenderData', {
                key: param.key,
                value: param.value,
                name: '临时创建缓存',
            });
        };
    },
    deleteCache(context, id) {
        // action=> 删除缓存数据
        window.action.cache.delete({
            id: id,
        }).then((res) => {
            if (res) {
                context.dispatch('getRenderData');
            };
        });
    },
    getCache(context, param) {
        param.callback(context.state.cacheObj[param.key]);
    }
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}